﻿using System.Diagnostics;
using System.Windows;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;
using System.Xml.Linq;
using System;
using System.Linq;
using TagCloudNewsLibrary;

namespace ScheduledTaskAgent1
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        private string agentName;

        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        static ScheduledAgent()
        {
            // Subscribe to the managed exception handler
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });

        }

        /// Code to execute on Unhandled Exceptions
        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                Debugger.Break();
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override void OnInvoke(ScheduledTask task)
        {
            TagDataService.Current.LoadCompletedEvent = new LoadCompletedEventHandler(LoadCompleted);
            TagDataService.Current.LoadFailedEvent = new LoadFailedEventHandler(LoadFailed);

            agentName = task.Name;

            TagDataService.Current.ForceLoad(true);
        }

        public void LoadCompleted()
        {
            try
            {
                //TODO: Add code to perform your task in background
                TagDataService.Current.UpdateTiles();

#if DEBUG
                ScheduledActionService.LaunchForTest(agentName, TimeSpan.FromSeconds(120));
#endif

            }
            catch (Exception)
            {
            }
            finally
            {
                NotifyComplete();
            }
        }

        public void LoadFailed()
        {
            NotifyComplete();
        }

    }
}